jQuery(function ($) {
    window.ContentList = Spine.Controller.create({
        elements: {
            ".request .path": "path",            
            ".result .content": "content",
            ".result .workIndicator": "workIndicator",
        },

        events: {
            "change .path": "pathchange",
            "click .search": "search",
            "click .refresh": "search"
        },

        proxied: ["pathchange", "search"],

        init: function () {
            Cofe.Models.EntryList.fetch();
            this.workIndicator.hide();
        },

        pathchange: function (e) {
            console.log("pathchange");
        },

        search: function (e) {
            console.log("search");
            var searchUrl = "/lookup/" + this.path[0].value + "?rel=list&json=true";
            this.entryList = Cofe.Models.EntryList.select(function (el) { return el.id == searchUrl; });
            
            this.workIndicator.hide();
            this.content.show();

            if (!this.entryList || this.entryList.length == 0 || 
                e.srcElement.className == "refresh") {
                this.entryList = Cofe.Models.EntryList.init({ url: searchUrl });
                this.entryList.bind("fetched", this.proxy(function (elist) {
                    this.entryList.save();
                    this.render();

                    this.workIndicator.hide();
                    this.content.show();
                }));
                this.entryList.bind("ajaxError", this.proxy(function (xhr, s, e) {
                    window.alert('error when fetching')
                }));

                this.workIndicator.show();
                this.content.hide();
                this.entryList.fetch();
            }
            else {
                this.render();
            }
        },

        render: function (e) {
            this.content.html($("#contentListTemplate").tmpl(this.entryList));
        }


    });
})